#include <stdio.h>
#include <errno.h>
#include <fcntl.h>


//////////////////////////////////////////
// Yet another copy program             //
// yacp.c                               // 
// by Werner Moser, Martin Poier, ITM12 //
// Version 1.0                          //
// 2012-04-26                           //
//////////////////////////////////////////


int main (int argc, char* argv[]){

	//there have to be exactly 2 arguments given: Source and Destination. Otherwise, the program produces a failure
	if(argc!=3){
		fprintf(stderr, "Wrong usage of yacp\n right usage: ./yacp <source file> <destination file>\n");
		return 1;
	}

	//putting the paths of Source and destination into variables
	char* source_p = argv[1];
	char* dest_p = argv[2];

	//opening the source-File and processing error handling
	int src = open(source_p, O_RDONLY);
	if (src < 0){

		if(errno == ENOENT){
			perror("Failure opening source File: ");
		}

		else if (errno == EACCES) {
            		perror("Failure opening source File: ");
        	}

		return 1;
	}

	
	//opening destination file with error handling
	int dest = open(dest_p, O_CREAT | O_WRONLY | O_EXCL, 1000);
	if (dest < 0){
		if(errno == EEXIST){
			perror("Failure opening destination File: ");
		}

		else if (errno == EACCES) {
            		perror("Failure opening destination File: ");
        	}

		return 1;
	}



	//the buffer for the copying process (only one byte to guarantee, that only the bytes in the file are copied)
	int *buffer[1];

	//int value to controll, if the copying-process works correctly.
	int controller = -1;


	//copying process
	while((controller = read(src, buffer, 1)) !=0){

		//if there is nothing to copy, controller stays on -1, and the program is stopped
		if(controller<0){
			fprintf(stderr, "Could not read\n");
			close(src);
			close(dest);
			return 1;
		}

		//if the program does not write the the correct byte, program stopps
		else if(controller!=write(dest, buffer, 1)){
			fprintf(stderr, "Could not write\n");
			close(src);
			close(dest);
			return 1;
		}





	}
	

	close(dest);
    	close(src);
    	return 0;
}
